<template>
  <div class="inside-comment">
    <div class="layout">
      <div class="list-back" @click="listBack"><el-icon><DArrowLeft /></el-icon>返回列表</div>
      <div class="notice-container">
        <div class="title">{{ noticeDetail.title }}</div>
        <div class="info">
          <div class="left-box">  
            <div class="time info-content"><span>发布时间：</span>{{ formatDate(noticeDetail.publishTime,"yyyy-MM-dd") }}</div>
            <div class="type info-content" v-if="!(noticeDetail.projectId && noticeDetail.needFormId)"><span>类型：</span>{{ convertedNoticeType }}</div>
            <div class="author info-content" v-if="!(noticeDetail.projectId && noticeDetail.needFormId) && noticeDetail.author"><span>作者：</span>{{ noticeDetail.author }}</div>
          </div>
          <div class="right-box">
            <!-- <el-icon title="导出"><TakeawayBox /></el-icon> -->
            <el-icon title="打印" @click="printNotice"><Printer /></el-icon>
          </div>
          <div class="bottom-line"></div>
        </div>
        <!-- 这里预计还需要做一个登录后才能查看的效果 和判断是否绑定项目 -->
        <div class="info-list" v-if="noticeDetail.projectId && noticeDetail.needFormId">
          <div class="info-item">
            <div class="name">发布时间</div>
            <div class="item-info">{{ formatDate(noticeDetail.publishTime,"yyyy-MM-dd") }}</div>
          </div>
          <div class="info-item">
            <div class="name">发布人</div>
            <div class="item-info">{{ noticeDetail.author }}</div>
          </div>
          <div class="info-item">
            <div class="name">招标预算</div>
            <div class="item-info">￥{{ noticeDetail.totalAmount }}</div>
          </div>
          <div class="info-item">
            <div class="name">公告类型</div>
            <div class="item-info">{{ convertedNoticeType }}</div>
          </div>
          <div class="info-item">
            <div class="name">招标状态</div>
            <div class="item-info">
              【{{ convertedNoticeProjectState }}】
            </div>
          </div>
          <div class="info-item">
            <div class="name">截止时间：</div>
            <div class="item-info">
              <div class="countdown-container">
                <div class="countdown-list">
                  <div class="countdown-item">
                    <div class="num">{{days}}</div>
                    <div class="unit">天</div>
                  </div>
                  <div class="countdown-item">
                    <div class="num">{{hours}}</div>
                    <div class="unit">时</div>
                  </div>
                  <div class="countdown-item">
                    <div class="num">{{minutes}}</div>
                    <div class="unit">分</div>
                  </div>
                  <div class="countdown-item">
                    <div class="num">{{seconds}}</div>
                    <div class="unit">秒</div>
                  </div>
                </div>
                <el-button class="sign-up-btn" @click="handlePreview(noticeDetail, '预览')" type="primary" style="height: 30px;" :disabled="canSignUp">{{signUpTitle}}</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="notice-sign-up">
          <el-button class="sign-up-btn" @click="handlePreview(noticeDetail, '预览')" type="primary" style="height: 30px;" :disabled="canSignUp">{{signUpTitle}}</el-button>
        </div>
        <div class="notice-detail">
          <div class="notice-title">招标正文</div>
          <div class="notice-content" v-html="noticeDetail.content"></div>
          <div class="description" v-if="noticeDetail.description"><span>相关说明</span><p>{{noticeDetail.description}}</p></div>
        </div>
      </div>
    </div>
    <!-- 填写表单  -->
    <el-dialog v-model="detailVisible" title="填写信息" width="800px" modal style="margin-top: 50px;max-width:90%">
      <FormEcho v-if="preViewFormInfo" :formData="preViewFormInfo" ref="childRef" height="60vh" :disabled="false" :showDevice="false" :simple="true"/>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addInstanceVisible = false">取消</el-button>
          <el-button type="primary" @click="appendInstance">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 提示绑定企业  -->
    <el-dialog v-model="userBound" title="提示" width="400px">
      <div>您还未绑定企业信息，请前往绑定！</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userBound = false">暂不绑定</el-button>
          <el-button type="primary" @click="toBound">去绑定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import { Printer, DArrowLeft } from "@element-plus/icons-vue";
import { getToken } from "@ruifox-cms/utils";
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  selectFrontNotice,
  hasApplyParticipateApplication,
  insertParticipateApplication,
  checkCertificateParticipateApplication,
 } from "@/api/supplier";
import { FormEcho } from "@ruifox-cms/components";
import { selectPaper, selectListPaperResult } from '@/api/form'
import { useStore } from 'vuex'
import { formatDate } from '@/utils/tools'
import { checkUser } from "@/api/supplier";

const store = useStore()
const hasToken = ref(!!getToken());



// 返回列表
const route = useRoute()
const props = route.query
const router = useRouter()
const listBack = () => {
  router.push({ 
    path: '/bidding/user/noticeList', 
  });
}

//打印
const printNotice = () => {
  window.print();
};

// 详情相关
const detailVisible = ref(false)
const signUpTitle = ref('立即报名')
const canSignUp = ref(true)
const handleLogin = () => {
  if (process.env.NODE_ENV === "development") {
    window.location.href =
      location.protocol +
      "//" +
      location.hostname +
      ":8100/login/index?redirect=" +
      location.href;
  } else {
    window.location.href =
      location.protocol +
      "//" +
      location.hostname +
      `${location.port ? `:${location.port}` : ""}` +
      "/ram/login/index?redirect=" +
      location.href;
  }
};

//获取公告详情
const noticeDetail = ref({});
const getNoticeDetail = async () => {
  const res = await selectFrontNotice({ id: props.id });
  if (res.code === 20000) {
    noticeDetail.value = res.data;
    endTime.value = res.data.endTime;
    //将type和projectstate转为文字
    //如果公告存在表单  判断用户是否已经填写过表单
    if(noticeDetail.value.needFormId != 0 && noticeDetail.value.projectId){
      await checkIfSignUp()
    }
    //判断项目状态
    if(noticeDetail.value.projectState == 1){
      canSignUp.value = true;
      signUpTitle.value = "未开始"
    } else if(noticeDetail.value.projectState == 3){
      canSignUp.value = true;
      signUpTitle.value = "已结束"
    }
  }
};

//查询用户是否已有提交记录
const checkIfSignUp = async () => {
  //检查当前企业是否有提交记录 已有的话禁用报名
  const enterpriseSignUpRes = await hasApplyParticipateApplication({projectId:noticeDetail.value.projectId})
  if(enterpriseSignUpRes.code === 20000 && enterpriseSignUpRes.data == true){
    canSignUp.value = true;
    signUpTitle.value = "已报名"
  } else{
    const res = await selectListPaperResult({paperId:noticeDetail.value.needFormId})
    //如果用户已有待审核或者审核通过的提交记录 将最新的其存入招标中
    let newResult = res.data[res.data.length - 1]
    if(res.code === 20000 && res.data[0] && (newResult.state == 0 || newResult.state == 1)){
      canSignUp.value = true;
      signUpTitle.value = "已报名"
      try {
        const addRess = await insertParticipateApplication({formResultId:newResult.resultId ,projectId:noticeDetail.value.projectId})
        if (addRess.code == 20000) {
          canSignUp.value = true;
          signUpTitle.value = "已报名"
        } 
      } catch (error) {
        console.log(error);
      }
    } else {
      canSignUp.value = false;
      signUpTitle.value = "立即报名"
    }
  }
  // console.log("能否报名",canSignUp.value);
};

//倒计时效果
const endTime = ref("");
const days = ref(0);
const hours = ref(0);
const minutes = ref(0);
const seconds = ref(0);

let timer;
const updateCountdown = () => {
  const now = new Date();
  const end = new Date(endTime.value);
  const diff = end - now;
  if (diff > 0) {
    const totalSeconds = Math.floor(diff / 1000);
    days.value = Math.floor(totalSeconds / 3600 / 24);
    hours.value = Math.floor((totalSeconds % (3600 * 24)) / 3600);
    minutes.value = Math.floor((totalSeconds % 3600) / 60);
    seconds.value = totalSeconds % 60;
  } else {
    days.value = 0;
    hours.value = 0;
    minutes.value = 0;
    seconds.value = 0;
    clearInterval(timer);
  }
};

onMounted(async() => {

  await getNoticeDetail()
  if (endTime.value != "") {
    updateCountdown();
    timer = setInterval(updateCountdown, 1000);
  }
});

//离开页面销毁定时器
onUnmounted(() => {
  clearInterval(timer);
});

// 表单预览
const showPreview = ref(false)
const preViewFormInfo = ref()
const preViewFormInfoLoading = ref(false)
const previewText = ref('')
const curForm = ref()


//进入系统时 判断用户是否绑定企业信息，如没有提示用户去绑定
const userBound = ref(false);
const userEnterpriseId = ref();
const boundenterprise = async () => {
  // return 11
  const res = await checkUser();
  if(res.data.enterpriseId){
    userEnterpriseId.value = res.data.enterpriseId
  }
  if (res.code === 20000) {
    if (res.data.isForbidden == true) {
      ElMessage.error("账号已禁用");
      return false;
    } else if (res.data.applyingNow == true) {
      ElMessage.warning("您的账号正在审核中，请耐心等待");
      return false;
    } else if (res.data.hasEnterprise == false) {
      //当前不是绑定企业页面
      if(route.path != '/bidding/user/Supplier'){
        userBound.value = true;
        return false;
      }
    } else if (res.data.hasEnterprise == true) {
      return true;
    }
  } else {
    return true;
  }
}
//检查用户报名凭证
const checkCertificate = async (projectId,enterpriseId) => { 
  const res = await checkCertificateParticipateApplication({
    projectId: projectId,
    enterpriseId: enterpriseId
  });
  if(res.code === 20000 && res.data.hasCertificateRequired == true) {
    return true
  } else {
    return false
  }
};

const toBound = () => {
  router.push("/bidding/user/Supplier");
  userBound.value = false;

};
const handlePreview = async (row, text) => {
  //判断用户是否登录
  if (!hasToken.value) {
    ElMessage({
      showClose: true,
      message: '请先登录',
      type: 'warning'
    })
    setTimeout(() => {
      handleLogin()
    }, 1000) // 延迟跳转登录页
    return
  }
  //判断用户是否绑定企业
  const isBound = await boundenterprise();
  console.log("isBound", isBound);
  if (!isBound) {
    return;
  }

  //检查用户资质
  const isCheck = await checkCertificate(row.projectId, userEnterpriseId.value)
  console.log("isCheck", isCheck);
  if (!isCheck) {
    ElMessage.warning("企业资质不满足投标要求")
    return;
  }

  detailVisible.value = true

  curForm.value = row
  previewText.value = text
  preViewFormInfoLoading.value = true
  let res = await selectPaper({ formId: row.needFormId })
  preViewFormInfo.value = res.data
  store.commit('formDesignInfo/SET_FORMINFO', res.data)
  preViewFormInfoLoading.value = false
  showPreview.value = true
}

//获取表单提交的数据
const childRef = ref(null);
const appendInstance = async () => {
  if (childRef.value) {
    try {
      const result = await childRef.value.submit(noticeDetail.value.needFormId, 0);
      console.log('子组件 submit 方法返回结果:', result);
      //如果在表单系统那边提交成功 当前用户状态改为已报名
      if (result) {
        detailVisible.value = false;
        canSignUp.value = true;
        signUpTitle.value = "已报名"
      }
    } catch (error) {
      console.error('调用子组件 submit 方法出错:', error);
    }
  }
};

// 定义计算属性
const convertedNoticeType = computed(() => {
  switch (noticeDetail.value.type) {
    case 1:
      return '招标公告';
    case 2:
      return '中标公告';
    case 3:
      return '下载标书';
    default:
      return '未知类型';
  }
});
const convertedNoticeProjectState = computed(() => {
  switch (noticeDetail.value.projectState) {
    case 1:
      return '未开始';
    case 2:
      return '报名中';
    case 3:
      return '已结束';
    default:
      return '未知类型';
  }
});

</script>
<style lang="scss">
.list-back{
  color: $black_2;
  font-size: 14px;
  line-height: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  i{
    margin-right: 3px;
  }
  &:hover{
    color: $mainColor;
  }
}
.notice-container {
  .title {
    text-align: center;
    font-size: 24px;
    color: $black;
    margin-top: 20px;
  }
  .info {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #D7D7D7;
    padding-bottom: 15px;
    position: relative;
    .left-box {
      display: flex;
      align-items: center;
      font-size: 14px;
      line-height: 14px;
      .info-content {
        color: $black_2;
        margin-right: 15px;
        span{
          color: #666;
        }
      }
    }
    .right-box {
      display: flex;
      align-items: center;
      i {
        font-size: 18px;
        color: #666;
        margin-left: 10px;
        &:hover {
          color: $mainColor;
        }
      }
    }
    .bottom-line{
      content: "";
      display: block;
      width: 40px;
      height: 2px;
      background-color: $mainColor;
      position: absolute;
      bottom: 0;
      left: 0;
    }
  }
  .info-list {
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
    border: 1px solid $borderColor;
    border-bottom: none;
    .info-item {
      width: 50%;
      display: flex;
      align-items: center;
      font-size: 14px;
      height: 42px;
      border-bottom: 1px solid $borderColor;
      .name {
        width: 150px;
        height: 100%;
        display: flex;
        align-items: center;
        color: $black_2;
        padding: 0 10px;
        box-sizing: border-box;
        background: $checkColor;
      }
      .item-info {
        color: $black;
        padding: 5px 10px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        flex: 1;
      }
      .status{
        color: $mainColor;
        width: 450px;
      }
      .countdown-container{
        display: flex;
        width: 100%;
        justify-content: space-between;
        align-items: center;
       
      }
      .countdown-list{
          display: flex;
          .countdown-item{
            display: flex;
            font-size: 14px;
            .num{
              width: 25px;
              height: 25px;
              background: $mainColor;
              color: white;
              font-weight: bold;
              display: flex;
              align-items: center;
              justify-content: center;
              border-radius: 3px;
            }
            .unit{
              color: $black;
              margin: 0 5px;
            }
          }
      }
    }
  }
  .notice-detail {
    margin-top: 20px;
    .notice-title {
      padding: 0 7px;
      border-left: 3px solid $mainColor;
      font-size: 16px;
    }
    .notice-content{
      margin-top: 20px;
      min-height: 200px;
    }
    .description{
      /* display: flex; */
      span {
        padding: 0 7px;
        border-left: 3px solid $mainColor;
        font-size: 16px;
      }
      p{
        font-size: 14px;
        color: $black_2;
        margin-top: 10px;
      }
    }
  }
  .notice-sign-up{
    display: none;
    margin-top: 10px;
  }
}
/* 隐藏不需要打印的元素 */
@media print {
  .no-print {
    display: none;
  }
}
@media (max-width: 960px){
  .layout{
    padding: 0 20px;
    box-sizing: border-box;
  }
  .notice-container{
    .title{
      font-size: 18px;
      margin-top: 10px;
    }
    .info{
      margin-top: 10px;
    }
    .info-list {
      .info-item {
        width: 100%;
         .name{
          width: 100px;
         }
      }
      .sign-up-btn{
        display: none;
      }
    }
    .notice-sign-up{
      display: flex;
      justify-content: end;
    }
    .notice-detail {
      margin-top: 10px;
    }
  } 
}
</style>
